package com.ethanJun.csdn.infrastructure.impl;

import com.alibaba.fastjson.JSON;
import com.ethanJun.csdn.config.CsdnApiProperties;
import com.ethanJun.csdn.domain.model.ArticleToolRequest;
import com.ethanJun.csdn.domain.model.ArticleToolResponse;
import com.ethanJun.csdn.domain.model.dto.ArticleRequestDTO;
import com.ethanJun.csdn.domain.model.dto.ArticleResponseDTO;
import com.ethanJun.csdn.infrastructure.ICSDNInterface;
import com.ethanJun.csdn.infrastructure.ICSDNService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import retrofit2.Call;
import retrofit2.Response;

import java.io.IOException;

/**
 * @author 衣立君
 * @date 2025/04/22 21:41
 **/
@Slf4j
@Service
public class CsdnServiceImpl implements ICSDNService {

    @Resource
    private ICSDNInterface csdnInterface;

    @Resource
    private CsdnApiProperties csdnApiProperties;

    @Override
    public ArticleToolResponse writerArticle(ArticleToolRequest request) throws IOException {
        ArticleRequestDTO articleRequestDTO = new ArticleRequestDTO();
        articleRequestDTO.setTitle(request.getTitle());
        articleRequestDTO.setMarkdowncontent(request.getMarkdownContent());
        articleRequestDTO.setContent(request.getContent());
        articleRequestDTO.setTags(request.getTags());
        articleRequestDTO.setDescription(request.getDescription());
        articleRequestDTO.setCategories(csdnApiProperties.getCategories());
        log.info("请求CSDN发帖req:{} ", JSON.toJSONString(articleRequestDTO));
        Call<ArticleResponseDTO> call = csdnInterface.saveArticle(articleRequestDTO, csdnApiProperties.getCookie());
        Response<ArticleResponseDTO> response = call.execute();

        log.info("CSDN响应结果:{} ", JSON.toJSONString(response));

        if (response.isSuccessful()) {
            ArticleResponseDTO articleResponseDTO = response.body();
            if (null == articleResponseDTO) return null;
            ArticleResponseDTO.ArticleData articleData = articleResponseDTO.getData();
            ArticleToolResponse articleFunctionResponse = new ArticleToolResponse();
            articleFunctionResponse.setCode(articleResponseDTO.getCode());
            articleFunctionResponse.setMsg(articleResponseDTO.getMsg());
            articleFunctionResponse.setArticleData(ArticleToolResponse.ArticleData.builder()
                    .url(articleData.getUrl())
                    .id(articleData.getId())
                    .qrcode(articleData.getQrcode())
                    .title(articleData.getTitle())
                    .description(articleData.getDescription())
                    .build());

            return articleFunctionResponse;
        }

        return null;
    }
}